package com.strongbj.iot.devices.dam.sub.dacai.request.handle;

import java.io.UnsupportedEncodingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.response.handle.v1.DAMV1Handle;
import com.strongbj.iot.devices.dam.response.handle.v1.TemperatureAndHumidityHandle;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;

/**
 * 更新传感器参数的处理
 * @author yuzhantao
 *
 */
public class UpdateSensorParamsHandle extends DAMV1Handle {
	private static Logger logger = LogManager.getLogger(TemperatureAndHumidityHandle.class.getName());
	private static final byte SCREEN_ID = (byte) 6; // 网络屏幕ID
	private static final DAMMessageFactory damMessageFactory = new DAMMessageFactory(); // DAM消息工厂
	protected final Timer taskTimer = new HashedWheelTimer();
	
	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if (t.getCommand() == 0x17) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {
		byte[] srcDatas = t.getDatas();
		// srcDatas数据段在DAM里有6个字节，代表6个传感器状态，0代表温度，1代表温湿度
		// 大彩里设置的传感器开启是0，关闭是1
		
		ITaskManager taskManager = DAMManager.getTaskManager(ByteUtil.byteArrToHexString(t.getAddressCode()));
		for(int i=0;i<srcDatas.length;i++) {
			if(srcDatas[i]==0) {
				byte controlId1 = Integer.valueOf(i*2+1).byteValue();
				taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
					@Override
					protected void taskRun() {
						try {
							UpdateSensorParamsHandle.this.sendMessage(ctx, t.getAddressCode(), SCREEN_ID, controlId1,(byte)0);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				
				byte controlId2 = Integer.valueOf(i*2+2).byteValue();
				taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
					@Override
					protected void taskRun() {
						try {
							UpdateSensorParamsHandle.this.sendMessage(ctx, t.getAddressCode(), SCREEN_ID, controlId2,(byte)1);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}else if(srcDatas[i]==1) {
				byte controlId1 = Integer.valueOf(i*2+1).byteValue();
				taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
					@Override
					protected void taskRun() {
						try {
							UpdateSensorParamsHandle.this.sendMessage(ctx, t.getAddressCode(), SCREEN_ID, controlId1,(byte)0);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				
				byte controlId2 = Integer.valueOf(i*2+2).byteValue();
				taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
					@Override
					protected void taskRun() {
						try {
							UpdateSensorParamsHandle.this.sendMessage(ctx, t.getAddressCode(), SCREEN_ID, controlId2,(byte)0);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			} 
		}
		
		return null;
	}

	private void sendMessage(ChannelHandlerContext ctx,byte[] devAddress,byte screenId, byte controlId, byte buttonState)
			throws UnsupportedEncodingException {
		byte[] datas = createUpdateButtonControlMessage(devAddress, screenId, controlId, buttonState);
		ChannelFuture cf = ctx.channel().writeAndFlush(Unpooled.copiedBuffer(datas));
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("向屏幕下发设置传感器状态成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("向屏幕下发设置传感器状态失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}

	private byte[] createUpdateButtonControlMessage(byte[] devAddress, byte screenId,byte controlId, byte buttionState)
			throws UnsupportedEncodingException {
		byte[] destDatas = new byte[] {(byte)0xEE,(byte)0xB1,(byte)0x10,(byte)0x00,screenId,0x00,controlId,0x00,(byte)0xFF,(byte)0xFC,(byte)0xFF,(byte)0xFF};
		// 大彩里设置的传感器开启是0，关闭是1
		destDatas[7]=buttionState;

		return damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()), devAddress, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				(byte) 0xFF, // 设置向大彩屏发命令的编号
				destDatas // 设置设备编号
		);
	}
}

